#!/bin/sh
# shellcheck shell=dash disable=SC2169
#
# Startup script to check for a backup restore
#

# function to check if a backup should be restored that had been placed in /usr/local/tmp
# in addition to /usr/local/.doBackupRestore being present and empty
check_backup_restore() {

  # only continue if .doBackupRestore file exists
  if [[ ! -r /usr/local/.doBackupRestore ]]; then
    return 1
  fi

  if [[ -f /usr/local/tmp/usr_local.tar.gz ]]; then
    # now remove the whole /usr/local, but keep /usr/local/tmp
    find /usr/local -not -name tmp -not -name "lost+found" -mindepth 1 -maxdepth 1 -exec rm -rf {} \;

    # unarchive the backup archive to restore everything
    tar -C / --warning=no-timestamp --no-same-owner -xf /usr/local/tmp/usr_local.tar.gz

    rm -f /usr/local/.doBackupRestore

    # make sure everything is written to disk
    sync

  else

    rm -f /usr/local/.doBackupRestore
    return 1

  fi

  return 0
}

start() {
  echo -n "Checking for Backup Restore: "

  if check_backup_restore; then
    echo "OK: backup successfully restored"
  else
    echo "not required"
  fi
}

restart() {
  start
}

case "$1" in
  start)
    start
  ;;
  stop)
    # nothing
  ;;
  restart|reload)
    restart
  ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit 0
